import Person.LocalUserInfo;
import Person.ReadFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/RegisterServlet")
/*@MultipartConfig*/
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String> formMap = new HashMap<String, String>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
            for (FileItem fi : list ) {
                String fieldName = fi.getFieldName();
                formMap.put(fieldName,fi.getString("utf-8"));
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        LocalUserInfo localUserInfo = new LocalUserInfo(formMap.get("username"),formMap.get("name"),formMap.get("password"),"game_logo.jpg",null,null);
        Jsonb jsonb = JsonbBuilder.create();
        String userJson =jsonb.toJson(localUserInfo);
        new ReadFile().setUserInfo(userJson);

        Map<String, String> user = new HashMap<String, String>();
        user.put("username", formMap.get("username"));
        user.put("name", formMap.get("name"));
        user.put("faculty_title", "NULL");
        user.put("group", "NULL");
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        response.sendRedirect("/info.jsp");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
